let jwt = require('jsonwebtoken');
let {secret} = require('./config');

function intercept(){
    return (req,res,next)=>{
        //验证token是否为空
        let {token=""} = req.headers;
        if(!token){
            res.json({code:201,data:null,msg:"token为空，请登录后访问"});
            return;
        }
        //验证token是否有效
        jwt.verify(token,secret,(err,decoded)=>{
            if(!err){
                //3、检查token是否在有效期内
                if(Date.now()>decoded.exp){
                    //token已过期了
                    res.json({code:208,data:null,msg:"token已过期，请重新登录"})
                    return;
                }else{
                    //一切正常
                    next()    
                }
    
            }else{
                res.json({code:208,data:null,msg:"token无效"})
                return;
            }
        })
    }
}


module.exports = intercept;